export function getFileExtension(filename) {
    // 检查是否有文件名
    if (!filename) return '';

    // 找到最后一个点（.）的位置
    const lastIndex = filename.lastIndexOf('.');

    // 如果没有找到点或者点是文件名的最后一个字符，则没有扩展名
    if (lastIndex === -1 || lastIndex === filename.length - 1) return '';

    // 截取最后一个点之后的所有字符，即为扩展名
    return filename.substring(lastIndex + 1);
}

export async function runTasksInParallel(tasks, maxConcurrent) {
    const queue = [...tasks];
    const running = [];

    const runNext = async () => {
        while (queue.length > 0 && running.length < maxConcurrent) {
            const task = queue.shift();
            running.push(task());
        }
        await Promise.race(running);
        for (let i = 0; i < running.length; i++) {
            let status = await promiseState(running[i]);
            status = status.status;
            if (status === 'rejected') {
                throw promiseState(running[i]).reason;
            }
            if (status === 'pending') {
                continue;
            }
            if (status === 'fulfilled') {
                running.splice(i, 1); // Remove finished task
            }
        }
        if (!running.length) {
            return;
        }
        await runNext();
    };

    await runNext();
}

function promiseState(promise) {
    const pendingState = { status: 'pending' };

    return Promise.race([promise, pendingState]).then(
        (value) =>
            value === pendingState ? value : { status: 'fulfilled', value },
        (reason) => ({ status: 'rejected', reason })
    );
}

export function clone(v) {
    return JSON.parse(JSON.stringify(v));
}

export function sleep(timeout) {
    return new Promise((resolve) => setTimeout(resolve, timeout));
}
